package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //校验参数 作者id必须存在 必须登录
        if (dto.getAuthorApUserId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"作者信息参数错误");
        }
        if (dto.getOperation() == null || (dto.getOperation() != 1 && dto.getOperation() != 0)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关注操作类型错误");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String apUserId = user.getId().toString();
        String followId = dto.getAuthorApUserId().toString();

        try {
            redisTemplate.multi();
            //如果是关注方法
            if (dto.getOperation().intValue() == 0) {
                Double score = redisTemplate.opsForZSet()
                        .score(UserRelationConstants.FOLLOW_LIST + apUserId, followId);
                //存在提示已关注
                if (score != null) {
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST, "您已关注");
                }
                //否则关注
                redisTemplate.opsForZSet()
                        .add(UserRelationConstants.FOLLOW_LIST + apUserId, followId, System.currentTimeMillis());
                //将自己添加进对方粉丝
                redisTemplate.opsForZSet()
                        .add(UserRelationConstants.FANS_LIST + followId, apUserId, System.currentTimeMillis());
            } else {//如果为取关方法
                //从关注列表删除
                redisTemplate.opsForZSet()
                        .remove(UserRelationConstants.FOLLOW_LIST + apUserId, followId);
                //从对方粉丝列表删除
                redisTemplate.opsForZSet()
                        .remove(UserRelationConstants.FANS_LIST + followId, apUserId);
            }
            redisTemplate.exec();
            return ResponseResult.okResult();
        }catch (Exception e){
            e.printStackTrace();
            redisTemplate.discard();
            throw e; // 向上抛
        }
    }
}